package com.szq.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szq.yygh.cmn.listener.DictListener;
import com.szq.yygh.cmn.mapper.DictMapper;
import com.szq.yygh.cmn.service.DictService;
import com.szq.yygh.hosp.model.cmn.Dict;
import com.szq.yygh.hosp.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * All rights Reserved, Designed By www.jx-lab.com
 * @Title: DictServiceImpl
 * @Description:
 * @author lixy
 * @date 2021/8/19 8:51
 * @version V1.0
 * @Copyright: www.jx-lab.com Inc. All rights reserved.
 * 注意：本内容仅限于众合景轩信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * 根据数据Id查询子数据列表
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        dicts.stream().forEach(t->{
            t.setHasChildren(isHasChildData(t.getId()));
        });
        return dicts;
    }

    /**
     * 判断是否有子节点数据
     * @param id
     * @return
     */
    private boolean isHasChildData(Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }

    /**
     * 导出数据字典
     */
    @Override
    public void expertDictData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode("数据字典", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        List<Dict> dicts = baseMapper.selectList(null);
        List<DictEeVo> dictEeVos = new ArrayList<>();
        dicts.stream().forEach(t->{
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(t, dictEeVo);
            dictEeVos.add(dictEeVo);
        });

        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典")
                    .doWrite(dictEeVos);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 导入数据字典
     * @param file
     */
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(dictCode)){
            map.put("value", value);
            Dict dict = queryByProperty(map);
            return dict.getName();
        }else{
            map.put("dict_code", dictCode);
            Dict dict = queryByProperty(map);
            map.clear();
            map.put("parent_id", dict.getId());
            map.put("value", value);
            dict = queryByProperty(map);
            return dict.getName();
        }
    }

    @Override
    public List<Dict> getByDictCode(String dictCode) {
        Map<String, Object> map = new HashMap<>();
        map.put("dict_code", dictCode);
        Dict dict = queryByProperty(map);
        List<Dict> dictList = this.findChildData(dict.getId());
        return dictList;
    }

    private Dict queryByProperty(Map<String, Object> params){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper();
        for(String key : params.keySet()){
            queryWrapper.eq(key, params.get(key));
        }
        Dict dict = baseMapper.selectOne(queryWrapper);
        return dict;
    }
}
